const storage = require("@system.storage");
module.exports = {
  random(min, max) {
    //返回从min到max的随机数
    return Math.floor(Math.random() * (max - min)) + min;
  },
  formatDate: function(year, month, date) {
    //根据输入的年月日返回标准的年月日： YYYY-MM-DD
    var tmp_date = `${year}-${month < 10 ? "0" + month : month}-${
      date < 10 ? "0" + date : date
    }`;
    return tmp_date;
  },
  fromTxtToJson: function(txt) {
    //字符串转json
    return JSON.parse(txt);
  },
  fromJsonToTxt: function(json) {
    //json转字符串
    return JSON.stringify(json).toString();
  },
  callBack(callback, data) {
    //判断回调的对象是否有success方法
    if (callback && callback.success) {
      //如果成功，则返回是否存在
      callback.success(data);
    }
  },
  initStorage(key) {
    //初始化本地缓存的Key值
    this.setStorage(key, "[]");
  },
  setStorage(key, value, callback) {
    //设置缓存
    storage.set({
      key: key,
      value: value,
      success: function() {
        if (callback && callback.success) callback.success();
      },
      fail: function(data, code) {
        console.log(`设置Storage失败，错误代码为${code}`);
      }
    });
  },
  getStorage(key, callback) {
    //获取缓存
    var _this = this;
    storage.get({
      key: key,
      success: function(data) {
        if (!data) {
          //如果没有数据，就初始化缓存
          _this.initStorage(key);
          if (callback && callback.success) callback.success([]);
        } else {
          if (callback && callback.success)
            callback.success(_this.fromTxtToJson(data)); //回调
        }
      },
      fail: function(data, code) {
        console.log(`获取Storage失败，错误代码为${code}`);
      }
    });
  }
};
